package com.rainripple.java.common.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.ls.DOMImplementationLS;
import org.xml.sax.InputSource;

import com.rainripple.java.common.log.Log;

public class XmlUtil {

	public static Document parseDom(String xmlStr) {
		try {
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
			Document doc = documentBuilder.parse(new InputSource(new ByteArrayInputStream(xmlStr.getBytes("UTF-8"))));
			return doc;
		} catch (Exception e) {
			Log.error(e);
		}
		return null;
	}

	public static Document parseDom(InputStream inputStream) {
		try {
			DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
			domfac.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
			DocumentBuilder dombuilder = domfac.newDocumentBuilder();
			Document doc = dombuilder.parse(inputStream);
			return doc;
		} catch (Exception e) {
			Log.error(e);
		}
		return null;
	}

	public static String asXml(Document doc) {
		String xml = null;
		if (null != doc) {
			try {
				DOMImplementationLS domImplementationLS = (DOMImplementationLS) doc.getImplementation();
				xml = domImplementationLS.createLSSerializer().writeToString(doc);
			} catch (Exception e) {
				Log.error(e);
			}
		}
		return xml;
	}

}
